 
#include "HttpRequest.h"
 
size_t call_wirte_func(const char *ptr, size_t size, size_t nmemb, std::string *stream)
{
	size_t len = size * nmemb;
	stream->append(ptr, len);
	return len;
}

HttpRequest::HttpRequest():
curl(NULL)
{




}


HttpRequest::~HttpRequest()
{
	if (curl){
		curl_easy_cleanup(curl);
	}
}

void HttpRequest::GlobalCleanup(){
	curl_global_cleanup();
}

void HttpRequest::GlobalInit(){
	curl_global_init(CURL_GLOBAL_ALL);
}

bool HttpRequest::Execute(std::string method, std::string url)
{
	curl = curl_easy_init();
	if (curl == NULL) return false;

	
	curl_easy_setopt(curl, CURLOPT_URL, url.c_str());

	curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, call_wirte_func);
	curl_easy_setopt(curl, CURLOPT_WRITEDATA, &szbuffer);
	code = curl_easy_perform(curl);
	
	if (CURLE_OK == code) {
		return true;
	}
	return false;
}

std::string & HttpRequest::GetString()
{
	/*std::string outString;
	int ret = Decode(szbuffer.c_str(), szbuffer.size(), outString);
	szbuffer = "";
	if (ret != 0)
	{
		szbuffer = "";
	}
	szbuffer = outString;*/
	return szbuffer;
}

int HttpRequest::GetErrorCode()
{
	return code;
}

bool HttpRequest::Post(std::string url, const char*value)
{
	curl = curl_easy_init();
	if (curl == NULL) return false;

	/*std::string outString;
	Encode(value, strlen(value), outString);*/

	curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
	curl_slist *headers = curl_slist_append(NULL,
		"Content-Type:application/json;charset=UTF-8");
	curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
	curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);
	curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
	//curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, call_wirte_func);
	//curl_easy_setopt(curl, CURLOPT_WRITEDATA, &szbuffer);

	curl_easy_setopt(curl, CURLOPT_POSTFIELDS, value);
	
	code = curl_easy_perform(curl);
	curl_slist_free_all(headers);
	
	if(curl) 
	{     
       curl_easy_cleanup(curl); // 使用完毕后清理
    }


	if (CURLE_OK == code) 
	{
		return true;
	}
	return false;
}

int HttpRequest::Encode(const char*src, int len, std::string &out)
{
	
	return 0;
}

int HttpRequest::Decode(const char*src, int len, std::string &out)
{
	
	return 1;
}